package top.yokey.shopai.main.fragment;

import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;

import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatTextView;

import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;

import top.yokey.shopai.R;
import top.yokey.shopai.main.adapter.MainCartAdapter;
import top.yokey.shopai.main.viewmodel.MainCartVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.base.BaseFragment;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zcom.view.PullRefreshView;
import top.yokey.shopai.zsdk.bean.CartBean;
import top.yokey.shopai.zsdk.data.GoodsBuyData;
import top.yokey.shopai.zsdk.data.GoodsData;

public class MainCartFragment extends BaseFragment {

    private final GoodsBuyData data = new GoodsBuyData();
    private final ArrayList<CartBean> arrayList = new ArrayList<>();
    private final MainCartAdapter adapter = new MainCartAdapter(arrayList);
    private AppCompatCheckBox mainCheckBox = null;
    private AppCompatTextView countTextView = null;
    private AppCompatTextView settlementTextView = null;
    private PullRefreshView mainPullRefreshView = null;
    private MainCartVM vm = null;

    @Override
    public View initView() {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_cart, null);
        mainCheckBox = view.findViewById(R.id.mainCheckBox);
        countTextView = view.findViewById(R.id.countTextView);
        settlementTextView = view.findViewById(R.id.settlementTextView);
        mainPullRefreshView = view.findViewById(R.id.mainPullRefreshView);
        return view;

    }

    @Override
    public void initData() {

        mainPullRefreshView.setAdapter(adapter);
        mainPullRefreshView.setCanLoadMore(false);
        vm = getVM(MainCartVM.class);

    }

    @Override
    public void initEvent() {

        mainCheckBox.setOnClickListener(view -> {
            for (int i = 0; i < arrayList.size(); i++) {
                for (int j = 0; j < arrayList.get(i).getGoods().size(); j++) {
                    arrayList.get(i).getGoods().get(j).setSelect(mainCheckBox.isChecked());
                }
                arrayList.get(i).setSelect(mainCheckBox.isChecked());
            }
            mainPullRefreshView.setComplete();
            checkSelectAll();
            calc();
        });

        settlementTextView.setOnClickListener(view -> App.get().startGoodsBuy(data));

        mainPullRefreshView.setOnClickListener(view -> {
            if (mainPullRefreshView.isError() || arrayList.size() == 0) {
                if (App.get().isMemberLogin()) {
                    getData();
                    return;
                }
                App.get().startMemberLogin();
            }
        });

        mainPullRefreshView.setOnRefreshListener(new PullRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {

            }
        });

        adapter.setOnItemClickListener(new MainCartAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, CartBean bean) {

            }

            @Override
            public void onClickStore(int position, CartBean bean) {
                App.get().startStore(bean.getStoreId());
            }

            @Override
            public void onClickCheck(int position, boolean select, CartBean bean) {
                arrayList.get(position).setSelect(select);
                for (int i = 0; i < arrayList.get(position).getGoods().size(); i++) {
                    arrayList.get(position).getGoods().get(i).setSelect(select);
                }
                mainPullRefreshView.setComplete();
                checkSelectAll();
                calc();
            }

            @Override
            public void onClickGoods(int position, int positionGoods, CartBean.GoodsBean bean) {
                App.get().startGoods(new GoodsData(bean.getGoodsId()));
            }

            @Override
            public void onClickGoodsDelete(int position, int positionGoods, CartBean.GoodsBean bean) {
                vm.delCart(position, positionGoods, bean.getCartId());
            }

            @Override
            public void onClickGoodsAdd(int position, int positionGoods, CartBean.GoodsBean bean) {
                String quantity = (ConvertUtil.string2Int(bean.getGoodsNum()) + 1) + "";
                vm.addCart(position, positionGoods, bean.getCartId(), bean.getGoodsId(), quantity);
            }

            @Override
            public void onClickGoodsSub(int position, int positionGoods, CartBean.GoodsBean bean) {
                String quantity = (ConvertUtil.string2Int(bean.getGoodsNum()) - 1) + "";
                if (!quantity.equals("0")) {
                    vm.subCart(position, positionGoods, bean.getCartId(), bean.getGoodsId(), quantity);
                }
            }

            @Override
            public void onClickGoodsCheck(int position, int positionGoods, boolean select, CartBean.GoodsBean bean) {
                boolean isSelect = true;
                arrayList.get(position).getGoods().get(positionGoods).setSelect(select);
                for (int i = 0; i < arrayList.get(position).getGoods().size(); i++) {
                    if (!arrayList.get(position).getGoods().get(i).isSelect()) {
                        isSelect = false;
                    }
                }
                arrayList.get(position).setSelect(isSelect);
                mainPullRefreshView.setComplete();
                checkSelectAll();
                calc();
            }
        });

    }

    @Override
    public void initObserve() {

        vm.getCartLiveData().observe(this, list -> {
            arrayList.clear();
            arrayList.addAll(list);
            checkSelectAll();
            calc();
        });

        vm.getCartDelLiveData().observe(this, data -> {
            if (arrayList.get(data.getPos()).getGoods().size() == 1) {
                arrayList.remove(data.getPos());
            } else {
                arrayList.get(data.getPos()).getGoods().remove(data.getPosGoods());
            }
            LiveEventBus.get(Constant.DATA_REFRESH).post(Constant.COMMON_ENABLE);
            checkSelectAll();
            calc();
        });

        vm.getCartAddLiveData().observe(this, data -> {
            arrayList.get(data.getPos()).getGoods().get(data.getPosGoods()).setGoodsNum(data.getData());
            LiveEventBus.get(Constant.DATA_REFRESH).post(Constant.COMMON_ENABLE);
            calc();
        });

        vm.getCartSubLiveData().observe(this, data -> {
            arrayList.get(data.getPos()).getGoods().get(data.getPosGoods()).setGoodsNum(data.getData());
            LiveEventBus.get(Constant.DATA_REFRESH).post(Constant.COMMON_ENABLE);
            calc();
        });

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                arrayList.clear();
                mainPullRefreshView.setError(bean.getReason());
                checkSelectAll();
                calc();
            } else {
                ToastHelp.get().show(bean.getReason());
            }
        });

    }

    @Override
    public void onResume() {

        super.onResume();
        if (App.get().isMemberLogin()) {
            getData();
            return;
        }
        mainCheckBox.setVisibility(View.GONE);
        settlementTextView.setVisibility(View.GONE);
        countTextView.setText(R.string.tipsLoginAccount);
        mainPullRefreshView.setError(getString(R.string.tipsLoginAccount));

    }

    //自定义方法

    private void calc() {

        int count = 0;
        float price = 0;
        String cartId = "";
        CartBean cartBean;
        CartBean.GoodsBean goodsBean;
        for (int i = 0; i < arrayList.size(); i++) {
            cartBean = arrayList.get(i);
            for (int j = 0; j < cartBean.getGoods().size(); j++) {
                goodsBean = cartBean.getGoods().get(j);
                if (goodsBean.isSelect()) {
                    int num = ConvertUtil.string2Int(goodsBean.getGoodsNum());
                    count += num;
                    price += ConvertUtil.string2Float(goodsBean.getGoodsPrice()) * num;
                    //noinspection StringConcatenationInLoop
                    cartId += goodsBean.getCartId() + "|" + num + ",";
                }
            }
        }
        if (!VerifyUtil.isEmpty(cartId)) cartId = cartId.substring(0, cartId.length() - 1);
        String temp = App.get().handlerHtml(String.format(App.get().getString(R.string.htmlCartSettlement), count + "", price + ""), "#FF0000");
        if (count == 0) {
            temp = getString(R.string.tipsCartEmpty);
        }
        countTextView.setText(Html.fromHtml(temp));
        if (arrayList.size() == 0) {
            mainCheckBox.setVisibility(View.GONE);
            settlementTextView.setVisibility(View.GONE);
            mainPullRefreshView.setEmpty();
        } else {
            mainCheckBox.setVisibility(View.VISIBLE);
            settlementTextView.setVisibility(View.VISIBLE);
            mainPullRefreshView.setComplete();
        }
        data.setIfcart("1");
        data.setCartId(cartId);

    }

    private void getData() {

        mainPullRefreshView.setLoad();
        vm.getCart();

    }

    private void checkSelectAll() {

        boolean isSelect = true;
        for (int i = 0; i < arrayList.size(); i++) {
            if (!arrayList.get(i).isSelect()) {
                isSelect = false;
            }
        }
        mainCheckBox.setChecked(isSelect);

    }

}
